package com.geek.project.geekverificationcodestarter.config;

import com.geek.project.geekredisstarter.service.RedisService;
import com.geek.project.geekverificationcodestarter.props.SmsProperties;
import com.geek.project.geekverificationcodestarter.props.VerifyCodeProperties;
import com.geek.project.geekverificationcodestarter.service.kaptcha.VerifyCodeService;
import com.geek.project.geekverificationcodestarter.service.kaptcha.impl.VerifyCodeServiceImpl;
import com.geek.project.geekverificationcodestarter.service.sms.SmsService;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
@ConditionalOnClass(value = {DefaultKaptcha.class})
@EnableConfigurationProperties(VerifyCodeProperties.class)
public class KaptchaAutoConfiguration {

    @Bean("defaultKaptcha")
    @ConditionalOnMissingBean(name = "defaultKaptcha")
    public DefaultKaptcha producer() {
        Properties properties = new Properties();
        properties.put(Constants.KAPTCHA_BORDER, "no");
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR, "black");
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_CHAR_SPACE, "10");
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4");
        properties.put(Constants.KAPTCHA_IMAGE_WIDTH, "120");
        properties.put(Constants.KAPTCHA_IMAGE_HEIGHT, "34");
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE, "25");
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_CHAR_STRING, "0123456789");
        properties.put(Constants.KAPTCHA_NOISE_IMPL, "com.google.code.kaptcha.impl.NoNoise");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }

    @Bean
    @ConditionalOnMissingBean(name = "verifyCodeService")
    @ConditionalOnBean(name = "defaultKaptcha")
    public VerifyCodeService verifyCodeService(DefaultKaptcha producer, RedisService redisService, SmsService smsService, SmsProperties smsProperties, VerifyCodeProperties verifyCodeProperties){
        return new VerifyCodeServiceImpl(producer, redisService, smsService, smsProperties, verifyCodeProperties);
    }
}